package com.jia.together.service.impl;

import com.jia.together.entity.Permission;
import com.jia.together.entity.User;
import com.jia.together.exception.MyException;
import com.jia.together.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;


@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {
    @Autowired
    private UserService userService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.selectByUsername(username);
        if (user == null){
            throw new MyException(40000,"没有该用户");
        }
        List<Permission> permissionList = userService.selectPermissionByUsername(username);
        List<GrantedAuthority> authorities = new ArrayList<>();
        permissionList.forEach(permission -> {
            String value = permission.getPermissionValue();
            if (!StringUtils.isEmpty(value)){
                authorities.add(new SimpleGrantedAuthority(value));
            }
        });
        user.setAuthorities(authorities);
        return user;
    }
}
